<?php
class VaildateCode {
	private $charset = 'ABCDEFGHKMNPRSTUVWXYZ23456789';        //随机字符因子
	private $code;
	private $codelen = 4;
	private $width = 145;
	private $height = 20;
	private $img;
	private $fontSize = 20;             //指定字体大小
	private $fontcolor;                 //指定字体颜色

	private function createCode() {
		//字符串下标的长度
		$len = strlen($this->charset) - 1;
		for($i = 0; $i < $this->codelen; $i++) {
			//随即获得字符串下标所对应的值
			$this->code .= $this->charset[mt_rand(0,$len)];
		}
	}

	//生成字体
	private function createFont() {
		//为每个字符分配均匀的长度
		$fontX = $this->width / $this->codelen;
		for($i = 0; $i < $this->codelen; $i++) {
			$this->fontcolor = imagecolorallocate($this->img,mt_rand(200,255),mt_rand(200,255),mt_rand(200,255));
			imagestring($this->img,5,$fontX*$i/2.6+46,$this->height / 7,$this->code[$i],$this->fontcolor);
		}
	}

	//生成背景图像
	private function createBg() {
        $this->img = imagecreatefrompng(ROOT_PATH.'/view/default/images/bg_code'.mt_rand(1,3).'.png');
	}

	//输出图像
	private function output() {
		header('Content-type:image/png');
		imagepng($this->img);
		imagedestroy($this->img);
	}

	//对外生成图像
	public function doimg() {
		$this->createBg();
		$this->createCode();
		//生成字符在线条前，可以覆盖线条，增强可见度
		$this->createFont();
		$this->output();
	}

	//获取验证码，用于以后的session验证验证码是否正确，为了使用户输入不区分大小写，把获取的验证码全部转化为小写
	public function getCode() {
		return strtolower($this->code);
	}

}


?>